﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pasteles.DataBase;
using System.IO.Ports;
using System.IO;
using System.Windows.Forms;

namespace Pasteles.Controler
{
    public class Printer
    {
        
        public string logfile = "";
        public StreamWriter log;
        public SerialPort _serialPort;

        public Printer(string logfile)
        {
            this.logfile = logfile;
        }
        // Safe Printer
        public void safePrinting(string sStringToPrint )
        {
            try
            {
                if (!_serialPort.IsOpen)
                    _serialPort.Open();
                try
                {
                    int iLen = sStringToPrint.Length;
                    string sTemp = "";
                    if (iLen > 128)
                    {
                        int div = iLen / 128; // Lay so nguyen 
                        int mod = iLen % 128; // Lay so du 
                        int j = 1;
                        for (int i = 0; i < div; i++)
                        {
                            sTemp = sStringToPrint.Substring(i * 128, 128);
                            _serialPort.Write(sTemp);
                            System.Threading.Thread.Sleep(500);
                            j = i;
                        }
                        sTemp = sStringToPrint.Substring(j * 128, mod);
                        _serialPort.Write(sTemp);
                        logToFile(sTemp);
                        System.Threading.Thread.Sleep(500);
                        _serialPort.Close();
                    }
                    else
                    {
                        _serialPort.Write(sStringToPrint);
                        System.Threading.Thread.Sleep(500);
                        _serialPort.Close();
                    }
                }
                catch (Exception ex)
                {
                    logToFile("None safe printing error: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                logToFile("Print bill error: " + ex.ToString());
            }
        }
        public void logToFile(string strLogText)
        {
            try
            {
                if (!File.Exists(logfile))
                {
                    log = new StreamWriter(logfile);
                }
                else
                {
                    log = File.AppendText(logfile);
                }
                log.WriteLine(DateTime.Now);
                log.WriteLine(strLogText);
                log.WriteLine();
                log.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Write log error");

            }
        }
    }
        
}
